package org.dromara.common.rocketmq.listener;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.rocketmq.constant.TransactionConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;

/**
 * 发送事务消息后，会调用这个类中的 executeLocalTransaction 方法【消费者】
 */
@RocketMQTransactionListener
public class RocketMQListener implements RocketMQLocalTransactionListener {

    private Logger log = LoggerFactory.getLogger(RocketMQListener.class);

    /**
     * 本地事务要不要执行
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        String transactionId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        log.info("事务id为：{}，检测本地事务",transactionId);
        String str = RedisUtils.getCacheObject(TransactionConstant.TX + transactionId);
        if (StringUtils.isEmpty(str) || TransactionConstant.UNKNOWN.equals(str)) {
            // 可能业务还没有处理完成，回查的时候在看看
            return RocketMQLocalTransactionState.UNKNOWN;
        }else if (TransactionConstant.ROLLBACK.equals(str)){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        // 提交事务，消息可以消费
        return RocketMQLocalTransactionState.COMMIT;
    }

    /**
     * 回查，事务要不要提交
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        String transactionId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
        log.info("事务id为：{}，回查本地事务",transactionId);
        String str = RedisUtils.getCacheObject(TransactionConstant.TX + transactionId);
        if (StringUtils.isEmpty(str) || TransactionConstant.UNKNOWN.equals(str)) {
            // 可能业务还没有处理完成，回查的时候在看看
            return RocketMQLocalTransactionState.UNKNOWN;
        }else if (TransactionConstant.ROLLBACK.equals(str)){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        // 提交事务，消息可以消费
        return RocketMQLocalTransactionState.COMMIT;
    }
}
